package thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock 可重入锁
 * 获取了外部锁就等于获取了内部锁(或者是外部内部实际上就只有1把锁)
 *
 *
 * Created on 2020/6/10.
 */

class Phone implements Runnable{

    public synchronized void sendSms(){
        System.out.println(Thread.currentThread().getName() + "\tsendSms");
        sendEmail();
    }

    public synchronized void sendEmail(){
        System.out.println(Thread.currentThread().getName() + "\tsendEmail");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //--------------------------------------------------------------------
    ReentrantLock lock = new ReentrantLock();//默认非公平锁
    @Override
    public void run() {
        get();
    }

    public void get() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\tget");
            set();
        }finally {
            lock.unlock();
        }
    }
    public void set() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\tset");

        }finally {
            lock.unlock();
        }
    }
}
public class ReentrantLockDemo {
    public static void main(String[] args) {
        Phone phone = new Phone();
       /* Thread t1 = new Thread(phone, "t1");
        t1.start();
        Thread t2 = new Thread(phone, "t2");
        t2.start();*/
        new Thread(()->{
            try {
                phone.sendEmail();
            }catch (Exception e){
                e.printStackTrace();
            }
        },"t2").start();

        new Thread(()->{
           try {
               phone.sendSms();
           }catch (Exception e){
               e.printStackTrace();
           }
       },"t1").start();



        new Thread(()->{
            try {
                phone.sendSms();
            }catch (Exception e){
                e.printStackTrace();
            }
        },"t3").start();
    }

}
